package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.SellerMapper;
import com.itheima.travel.pojo.Seller;
import com.itheima.travel.pojo.SellerExample;
import com.itheima.travel.req.SellerVo;
import com.itheima.travel.service.SellerService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Description：后台用户管理
 */
@Service
public class SellerServiceImpl implements SellerService {

    @Autowired
    private SellerMapper sellerMapper;

    @Autowired
    HttpSession session;

    @Override
    public Boolean registerSeller(SellerVo sellerVo) {
        Seller seller = BeanConv.toBean(sellerVo, Seller.class);
        seller.setPassword(MD5Coder.md5Encode(seller.getPassword()));
        int flag = sellerMapper.insert(seller);
        return flag>0;
    }

    @Override
    public SellerVo loginSeller(SellerVo sellerVo) {
        //组装条件
        SellerExample example = new SellerExample();
        example.createCriteria().andUsernameEqualTo(sellerVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(sellerVo.getPassword()));
        //查询list结果集
        List<Seller> sellers = sellerMapper.selectByExample(example);
        //转换VO
        List<SellerVo> list = BeanConv.toBeanList(sellers, SellerVo.class);
        //判断结果
        if (list.size()==1){
            SellerVo sellerVoResult = list.get(0);
            //放入会话
            String sessionId = session.getId();
            sellerVoResult.setSessionId(sessionId);
            session.setAttribute(sessionId,sellerVoResult);
            return sellerVoResult;
        }
        return null;
    }

    @Override
    public void loginOutSeller() {
        //从会话中删除当前对象
        session.removeAttribute(session.getId());
    }

    @Override
    public Boolean isLogin() {
        //根据当前用户是否存在判断登录状态
        Object sessionObject = session.getAttribute(session.getId());
        return !EmptyUtil.isNullOrEmpty(sessionObject);
    }

    @Override
    public SellerVo findSellerVoById(SellerVo sellerVo) {
        return BeanConv.toBean(sellerMapper.selectByPrimaryKey(sellerVo.getId()),SellerVo.class);
    }


}
